package day11.HomeWork;

import java.util.concurrent.locks.ReentrantLock;

//a.使用公平锁ReentrantLock实现3个线程交替打印1-100的数字，
// 保证每个线程获取锁的机会均等
public class Demo1 {
    ReentrantLock lock = new ReentrantLock(true);
    int sum = 0;

    public void printNum() {
        String name = Thread.currentThread().getName();
        lock.lock();
        if (sum < 100) {
            sum++;
            System.out.println(name + "打印了:" + sum);
        }
        lock.unlock();
    }

    public static void main(String[] args) {
        Demo1 d = new Demo1();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                while (d.sum != 100) {
                    d.printNum();
                }
            }, "线程" + i).start();
        }
    }
}
